import copy
import os

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from Notes.models import Note
from SecureHelperServer.settings import formatResponseData, MEDIA_ROOT
from utils.conf import Response, verifyID, newID
from utils.custom import MyJWTAuthentication


class SaveNoteView(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        保存Note
        """
        data = copy.deepcopy(formatResponseData)
        try:
            noteId = request.data.get("id")
            content = request.data.get("content")
            timeStamp = request.data.get("timeStamp")
            needRemoveImageVideoNameList = request.data.get("needRemoveImageVideoNameList")

            if not (content and timeStamp):
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            # 删除 已删除的 图片/视频
            for name in needRemoveImageVideoNameList:
                imagePath = os.path.join(MEDIA_ROOT, "userNotesMedia", "userNotesImages", name)
                videoPath = os.path.join(MEDIA_ROOT, "userNotesMedia", "userNotesVideos", name)
                if os.path.exists(imagePath): os.remove(imagePath)
                if os.path.exists(videoPath): os.remove(videoPath)

            # 存入note
            noteObj = {
                "content": content,
                "timeStamp": timeStamp,
                "user": request.user
            }

            if verifyID(noteId):
                noteObj["id"] = noteId
            else:
                noteObj["id"] = newID()

            note, isCreate = Note.objects.update_or_create(defaults=noteObj, id=noteObj["id"])
            note.save()

            return Response(data=data, responseMsg="保存成功", loggerMsg=f"保存Note：成功，noteId={noteId}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
